#!/home/catmd5/.venv/bin/python3.8
import warnings

warnings.filterwarnings(action='ignore', module='.*paramiko.*')

import json
import paramiko
import hashlib
import socket
from concurrent.futures import ThreadPoolExecutor
from cmd_line import Server

with open("./md5_config.json", 'r', encoding='utf-8') as fr:
    node_lists = json.load(fr)
node_list = node_lists['map_list']
VERSION = node_lists.get('version', "None")
all_robot_res = {}
all_robot_md5 = {}
robot_ip = {}
ip_head = node_lists["robot_ip"]
ip_range = node_lists['ip_range']


def test(ip):
    line = ''
    try:
        socket.setdefaulttimeout(5)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, 22))
        s.send(bytes("INFO\r\n", 'UTF-8'))
        result = s.recv(1024).decode()

        line = Server(ip, 22, "muyi", "muyi@123")
        line.connect()
        line.open_ssh()
        # mes = line.ssh_send_cmd('ls /mooe')
        mes = line.ssh_send_cmd('docker ps -q --filter "name=mooe-core"')
        if mes:
            # 镜像车
            node_base_path = '/mooe/'
            cmd = "md5sum " + node_base_path + (' ' + node_base_path).join(node_list)
            # print(cmd)
            r1 = line.ssh_send_cmd("cat /mooe/machineinfo/robot_id").strip("\n").strip() + "-docker"
            r2 = line.ssh_send_cmd(cmd)
        else:
            node_base_path = '/opt/ros/'
            cmd = "md5sum " + node_base_path + (' ' + node_base_path).join(node_list)
            # print(cmd)
            r1 = line.ssh_send_cmd("cat /opt/ros/machineinfo/robot_id").strip("\n").strip() + "    "
            r2 = line.ssh_send_cmd(cmd)
        m = hashlib.md5()
        m.update(r2.encode('utf-8'))
        return [r1, m.hexdigest()[:8], r2, ip]
    except:
        # print("err")
        pass
    finally:
        if line:
            line.close()
            del line


print("versions: %s" % VERSION)
if len(ip_range) != 2:
    ip_range = [2, 250]
with ThreadPoolExecutor(500) as pool:
    results = []
    for i in range(ip_range[0], ip_range[1] + 1):
        # if i + 1 == 109:
        ip = ip_head + str(i)
        results.append(pool.submit(test, ip))

    for res in results:
        r = res.result()
        if r is not None:
            all_robot_md5[r[0]] = r[1]
            all_robot_res[r[0]] = r[2].split('\n')
            robot_ip[r[0]] = r[3]

csv_arr = [",".join(["robot", "ip", "version", "mooe",
                     "地图内path_one", "地图内path_two", "地图内position_number",
                     "path内path_one", "path内path_two", "path内position_number", ])]
for robot in all_robot_res:
    csv_col = [robot, robot_ip[robot], all_robot_md5[robot]]

    for node in node_list:
        md5 = ''
        for res in all_robot_res[robot]:
            if res.find(node) == -1: continue
            md5 = (res.split(' ')[0])
            continue
        csv_col.append(md5[:8])

    csv_arr.append(','.join(csv_col))

print('\n'.join(csv_arr))
